package com.cgydu.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * projectName: day06_jdbc
 *
 * @author: CGY
 * time: 2020/7/30 14:47
 * description:获取连接的工具类！
 * 连接的来源 连接池 druid
 */
public class ConnectionUtils {

    private static DataSource dataSource = null;

    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    static {
        //在静态代码块中，进行druid连接池初始化工作！
        InputStream resourceAsStream = ConnectionUtils.class.getResourceAsStream("/database.properties");
        Properties properties = new Properties();
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataSource =
                    DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 预留返回连接池方法
     * @return
     */
    public static DataSource getDataSource() {
        return dataSource;
    }

    /**
     * 返回连接
     * @return 返回连接池中获取的连接
     */
    public static Connection getConnection() throws SQLException {

        Connection connection = threadLocal.get();

        if (connection == null)
        {
            connection = dataSource.getConnection();

            threadLocal.set(connection);
        }

        return connection;
    }


    public static void close(Connection connection, Statement statement) throws SQLException {
        if (connection != null) {
            connection.close();
        }

        if (statement != null) {
            statement.close();
        }
    }
    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if (connection != null) {
            connection.close();
        }

        if (statement != null) {
            statement.close();
        }

        if (resultSet != null) {
            resultSet.close();
        }
    }



    public static void startTransaction() throws SQLException {

        Connection connection = getConnection();

        connection.setAutoCommit(false);

    }

    public static void commit() throws SQLException {

        Connection connection = getConnection();

        connection.commit();

        threadLocal.remove();

    }


    public static void rollback() throws SQLException {
        Connection connection = getConnection();
        connection.rollback();
        threadLocal.remove();
    }

}
